//
//  XGL_userDataViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/20.
//

import UIKit

class XGL_userDataViewController: UIViewController,CustomNavgationBar{
    typealias Handler = ()->Void
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    private var inforView: XGL_UserDataView!
    private var middleView: XGL_UserDataMiddleView!
    private var gamesView: XGL_PersonalGamesView!
    private var bottomView: XGL_PersonalBottomView!
    private var userId: String = ""
    private var userSocialData: UserFollowAndFansNumData?
    private var userExtData: CompleteInfor?
    private var block: Handler?
    
    convenience init(userId: String,handler: Handler?) {
        self.init()
        self.block = handler
        self.userId = userId
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCustomBackgroundView()
        self.createXglView()
        self.creatClearNavigationBar(title: "")
        self.hudView.hudView.startAnimation()
        self.hudView.hudView.backgroundColor = .clear
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.equalToSuperview()
            make.bottom.equalTo(-PanTabbarH)
            make.top.equalTo(PanNavibarH)
        }
        self.getuserDataRequest()
        self.getIsFollowRequest()
        self.getRecievedGiftsRequest()
        self.getFollowFansNumerRequest()
        self.getMyPublishVideoDatasRequest()
    }
}

extension XGL_userDataViewController{
    private func handleuserData(){
        if let infor = self.userExtData{
            self.inforView.nameText.text = infor.data1
            self.inforView.headerView.loadImageWithUrl(infor.data2)
            self.inforView.idText.text = "ID:\((infor.userId % 2000000000).description)"
            if infor.data3 == 0{
                self.inforView.genderIconView.image = imageWithName("icon_xgl_user_female")
            }else{
                self.inforView.genderIconView.image = imageWithName("icon_xgl_user_male")
            }
            self.gamesView.games = infor.data4.components(separatedBy: ",").filter({$0.isEmpty == false})
            self.getIsFollowRequest()
        }else if let infor = self.userSocialData{
            self.inforView.nameText.text = infor.nickname
            self.inforView.headerView.loadImageWithUrl(infor.header)
            self.inforView.idText.text = "ID:\((infor.id % 2000000000).description)"
            if infor.gender == 0{
                self.inforView.genderIconView.image = imageWithName("icon_xgl_user_female")
            }else{
                self.inforView.genderIconView.image = imageWithName("icon_xgl_user_male")
            }
            self.gamesView.games = []
            self.getIsFollowRequest()
        }
    }
}

extension XGL_userDataViewController{
    private func getuserDataRequest(){
        self.hudView.hudView.startAnimation()
        self.hudView.hudView.backgroundColor = .clear
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        PanRequestManager<XGL_RequestBaseResponse<CompleteInfor>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .userData(userId: self.userId))) { result in
            switch result{
            case .success(let response):
                if let result = response.resultData {
                    self.userExtData = result
                    self.handleuserData()
                }
                break
            default:
                break
            }
        }
    }
    
    private func getIsFollowRequest(){
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .IsFollowUser(userId: self.userId))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                if let followResult = NSInteger(response.resultJson){
                    self.middleView.asFollow = followResult == 1
                }
                break
            default:
                break
            }
        }
    }
    
    private func getFollowFansNumerRequest(){
        PanRequestManager<XGL_RequestBaseResponse<UserFollowAndFansNumData>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .UserFollowsAndFansNum(userId: self.userId))) { result in
            switch result{
            case .success(let response):
                if let data = response.resultData {
                    self.userSocialData = data
                    self.handleuserData()
                    self.inforView.fansItem.title = data.followerNumber.description
                    self.inforView.followItem.title = data.followingNumber.description
                }
                break
            default:
                break
            }
        }
    }
    
    private func getRecievedGiftsRequest(){
        PanRequestManager<XGL_RequestBaseResponse<GiftData>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .RecievedGifts(userId: self.userId))) { result in
            switch result{
            case .success(let response):
                if let datas = response.resultDatas {
                    self.inforView.giftsItem.title = datas.filter({$0.num > 0}).count.description
                }
                break
            default:
                break
            }
        }
    }
    
    private func getMyPublishVideoDatasRequest(){
        PanRequestManager<XGL_RequestBaseResponse<PageModel<PublishData>>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .GetPublishData(userId: self.userId, page: self.bottomView.myPostSegmentView.pageIndex, size: 20, data1: "2", pid: nil, data5: nil))) { result in
            switch result{
            case .success(let response):
                self.hudView.dismiss()
                if let model = response.resultData{
                    if self.bottomView.myPostSegmentView.header.isRefreshing{
                        self.bottomView.myPostSegmentView.videosData = model.data
                        self.bottomView.myPostSegmentView.header.endRefreshing()
                        self.bottomView.myPostSegmentView.footer.resetNoMoreData()
                    }else if self.bottomView.myPostSegmentView.footer.isRefreshing{
                        self.bottomView.myPostSegmentView.videosData.append(contentsOf: model.data)
                        self.bottomView.myPostSegmentView.footer.endRefreshing()
                    }else{
                        self.bottomView.myPostSegmentView.videosData = model.data
                    }
                    if model.totalPages <= model.currentPage{
                        self.bottomView.myPostSegmentView.footer.endRefreshingWithNoMoreData()
                    }
                    self.bottomView.myPostSegmentView.collectionView.reloadData()
                }
                break
            default:
                self.hudView.dismiss()
                break
            }
        }
    }
    
    func addBlacklistRequest(){
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        PanRequestManager<XGL_RequestBaseResponse<SendGiftResult>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .AddBlacklist(userId: self.userId))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                XGL_Notice.default.post(name: XGL_Notification.addBlack.notificationName, object: ["userId":self.userId])
                self.navigationController?.popViewController()
                if let action = self.block {
                    action()
                }
                break
            default:
                break
            }
        }
    }
    
    private func followRequest(id: String,asFollow: Bool){
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .Follow(userId: id, isFollow: asFollow))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                self.middleView.asFollow = asFollow
                break
            default:
                break
            }
        }
    }
    
}

extension XGL_userDataViewController{
    @objc private func fansItemAction(){

    }
    @objc private func followItemAction(){

    }
    @objc private func giftsItemAction(){
        let vc = XGL_PersonalReceivedGiftsViewController()
        vc.userId = self.userId
        self.navigationController?.pushViewController(vc)
    }
    @objc private func followUserAction(){
        self.followRequest(id: self.userId, asFollow: true)
    }
    @objc private func userDataVideoAction(){
        let vc = XGL_MessageChatVideoViewController()
        if let infor = self.userExtData {
            vc.name = infor.data1
            vc.header = infor.data2
        }else if let infor = self.userSocialData{
            vc.name = infor.nickname
            vc.header = infor.header
        }
        vc.modalPresentationStyle = .fullScreen
        self.present(vc, animated: true)
    }
    @objc private func userDataMessageAction(){
        let vc = XGL_MessageChatViewController()
        vc.userId = self.userId
        if let infor = self.userExtData {
            vc.userName = infor.data1
            vc.userHead = infor.data2
        }else if let infor = self.userSocialData{
            vc.userName = infor.nickname
            vc.userHead = infor.header
        }
        vc.blackHandler = {
            self.navigationController?.popToRootViewController(animated: true)
        }
        self.navigationController?.pushViewController(vc)
    }
    @objc private func userDataMoreAction(){
        let actionController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let action = UIAlertAction(title: "Report", style: .default) { _ in
            if let infor = self.userExtData {
                let vc = XGL_ReportReasonViewController()
                vc.id = infor.id
                self.navigationController?.pushViewController(vc)
            }
        }
        let action1 = UIAlertAction(title: "Block", style: .default) { _ in
            self.alertPicker(message: "Whether to blocklist him ？") { [weak self] in
                guard let `self` = self else { return }
                self.addBlacklistRequest()
            }
        }
        
        let action2 = UIAlertAction(title: "Unfollow", style: .default) { _ in
            self.followRequest(id: self.userId, asFollow: false)
        }
        
        let action3 = UIAlertAction(title: "Cancel", style: .cancel)
        actionController.addAction(action)
        actionController.addAction(action1)
        actionController.addAction(action2)
        actionController.addAction(action3)
        self.present(actionController, animated: true)
    }
}

extension XGL_userDataViewController: PanSegmentViewDelegate{
    func refresh(view: MXCommonModule.PanSegmentView) {
        if view == self.bottomView.myPostSegmentView{
            self.bottomView.myPostSegmentView.pageIndex = 1
            self.getMyPublishVideoDatasRequest()
        }
    }
    
    func getMore(view: MXCommonModule.PanSegmentView) {
        if view == self.bottomView.myPostSegmentView{
            self.getMyPublishVideoDatasRequest()
        }
    }
    
    func didSelectRow(view: MXCommonModule.PanSegmentView, section: NSInteger, index: NSInteger) {
        if view == self.bottomView.myPostSegmentView{
            let model = self.bottomView.myPostSegmentView.videosData[index]
            if model.data4 == "1"{
                let vc = XGL_PersonalImageDetailViewController()
                vc.detailData = model
                vc.handler = {
                    self.bottomView.myPostSegmentView.header.beginRefreshing()
                }
                self.navigationController?.pushViewController(vc)
            }else{
                let vc = XGL_PersonalVideoDetailViewController()
                vc.detailData = model
                vc.handler = {
                    self.bottomView.myPostSegmentView.header.beginRefreshing()
                }
                self.navigationController?.pushViewController(vc)
            }
           
        }
    }
    
    func selectMoreAction(view: MXCommonModule.PanSegmentView, section: NSInteger) {
        
    }
    
    
}

extension XGL_userDataViewController{
    private func alertPicker(message: String,handler:@escaping ()->Void){
        let actionController = UIAlertController(title: "Warm reminder", message: message, preferredStyle: .alert)
        let action3 = UIAlertAction(title: "Sure", style: .default) { _ in
            handler()
        }
        let action2 = UIAlertAction(title: "Cancel", style: .cancel)
        actionController.addAction(action2)
        actionController.addAction(action3)
        self.present(actionController, animated: true)
    }
}

extension XGL_userDataViewController{
    private func createXglView(){
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        self.view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        let contentView = UIView()
        scrollView.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.edges.equalTo(scrollView)
            make.width.equalTo(scrollView)
        }
        self.inforView = XGL_UserDataView().then({ make in
            make.fansItem.itemButton.addTarget(self, action: #selector(self.fansItemAction), for: .touchUpInside)
            make.followItem.itemButton.addTarget(self, action: #selector(self.followItemAction), for: .touchUpInside)
            make.giftsItem.itemButton.addTarget(self, action: #selector(self.giftsItemAction), for: .touchUpInside)
        })
        self.middleView = XGL_UserDataMiddleView().then({ make in
            make.followItem.addTarget(self, action: #selector(self.followUserAction), for: .touchUpInside)
            make.videoItem.addTarget(self, action: #selector(self.userDataVideoAction), for: .touchUpInside)
            make.messageItem.addTarget(self, action: #selector(self.userDataMessageAction), for: .touchUpInside)
            make.moreItem.addTarget(self, action: #selector(self.userDataMoreAction), for: .touchUpInside)
        })
        self.gamesView = XGL_PersonalGamesView()
        self.bottomView = XGL_PersonalBottomView(titles: ["Release"]).then({ make in
            make.myPostSegmentView.delegate = self
        })
        contentView.addSubviews([inforView,middleView,gamesView,bottomView])
       
        inforView.snp.makeConstraints { make in
            make.width.centerX.top.equalToSuperview()
        }
        middleView.snp.makeConstraints { make in
            make.centerX.width.equalToSuperview()
            make.top.equalTo(inforView.snp.bottom).offset(24.0)
        }
        gamesView.snp.makeConstraints { make in
            make.centerX.width.equalToSuperview()
            make.top.equalTo(middleView.snp.bottom).offset(24.0)
        }
        bottomView.snp.makeConstraints { make in
            make.centerX.width.equalToSuperview()
            make.top.equalTo(gamesView.snp.bottom).offset(24.0)
            make.height.equalTo(conversionWithScrennWidth(value: 400.0))
        }
        contentView.snp.makeConstraints { make in
            make.bottom.equalTo(bottomView)
        }
    }
}
